package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.dao.CommonMapper;
import com.drd.dt.modular.dao.OrderMapper;
import com.drd.dt.modular.dao.UserMoneyMapper;
import com.drd.dt.modular.dto.GoodsDetailDTO;
import com.drd.dt.modular.entity.Order;
import com.drd.dt.modular.entity.User;
import com.drd.dt.modular.service.PDDService;
import com.drd.dt.properties.PDDPropertyConfig;
import com.drd.dt.util.FilterGoodsUtil;
import com.drd.dt.util.HttpConnectionPoolUtil;
import com.drd.dt.util.ResultUtil;
import com.drd.dt.util.StringUtil;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.request.PddDdkOrderListRangeGetRequest;
import com.pdd.pop.sdk.http.api.request.PddDdkThemeListGetRequest;
import com.pdd.pop.sdk.http.api.request.PddDdkThemePromUrlGenerateRequest;
import com.pdd.pop.sdk.http.api.response.PddDdkOrderListRangeGetResponse;
import com.pdd.pop.sdk.http.api.response.PddDdkThemeListGetResponse;
import com.pdd.pop.sdk.http.api.response.PddDdkThemePromUrlGenerateResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.drd.dt.util.StringUtil.getSecondTimestamp;

/**
 * Created by 86514 on 2019/3/21.
 */
@Service
@Transactional
public class PDDServiceImpl implements PDDService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private PDDPropertyConfig pddPropertyConfig;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoldCoinServiceImpl goldCoinService;
    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private FilterGoodsUtil filterGoodsUtil;
    @Autowired
    private UserMoneyServiceImpl testMoneyService;
    @Autowired
    private UserMoneyMapper userMoneyMapper;
    @Autowired
    private FilterGoodsUtil goodsUtil;

    /**
     * 获取拼多多订单
     */
    @Override
    public Tip getOrderListByCustomer(String start_time, String end_time,String type) throws Exception {
        logger.info("【黑桃省钱getOrderListByCustomer开始获取拼多多订单...】");
        if (StringUtils.isEmpty(type)){
            type = "1";
        }//1:更新时间查 2:支付时间查
        //获取用户pddid
        List pddOrderList = new ArrayList();
        if (type.equals("1")){
            pddOrderList = getPddOrderList(start_time, end_time);//从拼多多更新时间查订单数据
        }
        if (type.equals("2")){
            pddOrderList = getPddOrderListByPayTime(start_time, end_time);//从拼多多支付时间查订单数据
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String pId = pddPropertyConfig.getPid();//自购pid
        String sharePId = pddPropertyConfig.getChannelId();//分享pid
        //遍历拼多多订单列表处理
        SimpleDateFormat y_m_d_h_m_s = Constant.y_M_d_H_m_s;
        String our_time = "2019-12-03 18:00:00";//这之前的订单不进库
        for (Object list:pddOrderList){
            JSONObject pddOrder = JSON.parseObject(JSON.toJSONString(list));
            if (pddOrder.getString("p_id").equals(pId) || pddOrder.getString("p_id").equals(sharePId)) {
                Integer orderStatus = pddOrder.getIntValue("order_status");
                String order_id = pddOrder.getString("order_sn");
                String order_create_time = StringUtil.getTimestampDate(pddOrder.getString("order_create_time"));

                if (y_m_d_h_m_s.parse(order_create_time).getTime() < y_m_d_h_m_s.parse(our_time).getTime()) {
                    continue;
                }

                //获取订单
                Order RepeatOrder = orderMapper.getRepeatOrder(order_id);

                Integer status = reStatus(orderStatus);
                if (RepeatOrder != null) {//2,存在的话直接 更新
                    Integer myStatus = RepeatOrder.getStatus();
                    if (myStatus == 2) {
                        Map map = new HashMap();
                        map.put("status", status);
                        map.put("order_id", order_id);
                        if (orderStatus == 5) {// 订单结算既开始返佣
                            String clear_time = sdf.format(new Date(pddOrder.getLong("order_modify_at") * 1000));
                            String goods_id = String.valueOf(pddOrder.getDouble("goods_id"));
                            Double rake_back = pddOrder.getDouble("promotion_amount") / 100;
                            logger.info("【黑桃省钱开始更新拼多多订单号为 【" + order_id + "】的订单佣金...】");
//                            goodsUtil.rakeMoneyNew(order_id, rake_back, goods_id, clear_time, 0.0);//返佣金
                        } else if (myStatus != status) {
                            logger.info("【黑桃省钱开始更新拼多多订单号为 【" + order_id + "】的订单状态...】");
                            orderMapper.updateOrderStatus(map);//更新order表
                            RepeatOrder.setStatus(status);
                            testMoneyService.updateOrderFansRake(RepeatOrder);

                        }
                    }
                } else {//添加
                    Integer user_id = 0;
                    if (pddOrder.containsKey("custom_parameters")) {//有透传字段
                        user_id = pddOrder.getInteger("custom_parameters");
                    }
                    if (!StringUtils.isEmpty(user_id) && user_id > 0) {
                        Order order = new Order();
                        if (pddOrder.getString("p_id").equals(sharePId)) {
                            order.setBuytype(1);
                        } else {
                            order.setBuytype(0);
                        }
                        order.setProduct_id(pddOrder.getString("goods_id"));
                        order.setProduct_pic_url(pddOrder.getString("goods_thumbnail_url"));
                        order.setProduct_name(pddOrder.getString("goods_name"));
                        order.setUser_id(user_id);
                        order.setOrder_id(order_id);
                        order.setType(3);
                        order.setStatus(status);
                        order.setNumber(pddOrder.getInteger("goods_quantity"));
                        double order_amount = Double.valueOf(pddOrder.getString("order_amount")) / 100;
                        order.setActual_amount(String.format("%.2f", order_amount));
                        double promotion_amount = Double.valueOf(pddOrder.getString("promotion_amount")) / 100;
                        order.setRake_back(String.format("%.2f", promotion_amount));
                        order.setCreate_time(order_create_time);
                        //使用红包
                        Integer redpacket = 0;
                        try {
                            redpacket = goldCoinService.userRedpacket(String.valueOf(user_id));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        order.setRedpacket(redpacket);
                        Map mapuser = new HashMap();
                        mapuser.put("id", user_id);
                        User user = userMoneyMapper.getByUserId(mapuser);
                        double rate = testMoneyService.getRakeBackRatebyUser(user);
                        order.setUser_rake(String.valueOf(rate));
                        order.setUser_rake_back_yugu(testMoneyService.round(String.valueOf(rate * promotion_amount)));
                        order.setUser_rake_back("0");
                        orderMapper.insert(order);
                        if (null != user && order != null && promotion_amount > 0) {
                            testMoneyService.updateOrderFansRake(user, order);//新增加订单
                        }
                    }
                }
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 拼多多搜索
     *
     * @return
     */
    @Override
    public Tip goodsSearch(String keyword, String page, String sortType, String ifcoupon, Integer user_id) throws Exception {
        Map<String, Object> map = new HashMap<>();//装所有参数，进行转换
        keyword = StringUtil.getKeyword(keyword);
        //搜索关键字 拼接
        switch (keyword) {
            case "洗发造型":
                keyword = "洗发";
                break;
            case "个人护理":
                keyword = "护理";
                break;
            case "运动鞋服":
                keyword = "运动服装";
                break;
            case "户外鞋服":
                keyword = "户外服装";
                break;
            case "萌猫":
                keyword = "猫活体";
                break;
            case "萌狗":
                keyword = "狗活体";
                break;
        }
        if (!StringUtils.isEmpty(keyword) && keyword.length() > 50) {
            keyword = keyword.substring(0, 45);
        }
        List result = new ArrayList();
        Integer page_size = Constant.PAGE_SIZE_20; //条数
        if (StringUtils.isEmpty(page)) {
            page = "1"; //页码
        }
        /*asc:从低到高排序； desc:从高到低排序 （sort不为空时必填）排序方式:0-综合排序;1-按佣金比率升序;
        2-按佣金比例降序;3-按价格升序;4-按价格降序;5-按销量升序;6-按销量降序;7-优惠券金额排序升序;
        8-优惠券金额排序降序;9-券后价升序排序;10-券后价降序排序;11-按照加入多多进宝时间升序;
        12-按照加入多多进宝时间降序;13-按佣金金额升序排序;14-按佣金金额降序排序;15-店铺描述评分升序;
        16-店铺描述评分降序;17-店铺物流评分升序;18-店铺物流评分降序;19-店铺服务评分升序;20-店铺服务评分降序;
        27-描述评分击败同类店铺百分比升序，28-描述评分击败同类店铺百分比降序，29-物流评分击败同类店铺百分比升序，
        30-物流评分击败同类店铺百分比降序，31-服务评分击败同类店铺百分比升序，32-服务评分击败同类店铺百分比降序
        */
        String data_type = "JSON";//响应格式
        String type = "pdd.ddk.goods.search";//API接口名称
        String timestamp = StringUtil.getSecondTimestamp(new Date());//到秒的时间戳
        String client_id = pddPropertyConfig.getClientId();
        map.put("type", type);
        map.put("client_id", client_id);
        map.put("keyword", keyword);
        map.put("data_type", data_type);
        map.put("page", page);
        map.put("page_size", page_size);
        map.put("timestamp", timestamp);
        map.put("with_coupon", Boolean.parseBoolean(ifcoupon));
        map.put("sort_type", sortType);
        String sign = StringUtil.sortByMapKey(map, pddPropertyConfig.getClientSecret());//进行转换，返回md5加密的大写
        String entity = ("client_id=" + client_id + "&type=" + type + "&keyword=" + keyword + "&data_type=" + data_type + "&page=" +
                page + "&page_size=" + page_size + "&timestamp=" + timestamp + "&sort_type=" + sortType + "&with_coupon=" + Boolean.parseBoolean(ifcoupon) + "&sign=" + sign);
        String resultStr = HttpConnectionPoolUtil.postCommandFromNet2(pddPropertyConfig.getPddsearchUrl(), entity);
        //pdd返回数据处理
        if (!StringUtils.isEmpty(resultStr)) {
            JSONObject resultObj = JSON.parseObject(resultStr);
            JSONArray arrs = resultObj.getJSONObject("goods_search_response").getJSONArray("goods_list");
            for (Object info : arrs) {
                JSONObject detail = (JSONObject) info;
                GoodsDetailDTO detailDTO = new GoodsDetailDTO();
                Double promotion_rate = detail.getDouble("promotion_rate"); //比例 千分比
                Double min_group_price = detail.getDouble("min_group_price");//最小拼团价格 单位分
                Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);//公司返佣比例
                Double coupon_discount = detail.getDouble("coupon_discount") / 100;//优惠卷价格

                detailDTO.setType(3);
                String goodsName = detail.getString("goods_name") == null ? "" : detail.getString("goods_name");
                detailDTO.setGoodsName(goodsName);
                detailDTO.setGoodsId(detail.getString("goods_id") == null ? "" : detail.getString("goods_id"));
                detailDTO.setGoodsMainPicture(detail.getString("goods_thumbnail_url") == null ? "" : detail.getString("goods_thumbnail_url"));
                detailDTO.setGoodsDesc(detail.getString("goods_desc") == null ? "" : detail.getString("goods_desc"));
                detailDTO.setCoupon(String.format("%.2f", coupon_discount));// 优惠卷
                //计算
                Double original_price = min_group_price / 100; //原价
                detailDTO.setPrice(String.format("%.2f", original_price));
                //是否有优惠卷
                Boolean has_coupon = false;
                if (detail.containsKey("has_coupon")) {
                    has_coupon = detail.getBoolean("has_coupon");
                }
                detailDTO.setIfCoupon(has_coupon);
                //领劵后的价格
                Double price_after_coupon = original_price - (has_coupon == true ? coupon_discount : 0);
                detailDTO.setPriceAfterCoupon(String.format("%.2f", price_after_coupon));
                String sales_tip = detail.getString("sales_tip");// 销量
                if (sales_tip == null) {
                    detailDTO.setSales("0");// 销量
                } else {
                    detailDTO.setSales(sales_tip);// 销量
                }
                // 反拥金
                Double commission = (promotion_rate / 1000) * price_after_coupon * reback_money.doubleValue();
                Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                Double upcommission = (promotion_rate / 1000) * price_after_coupon * upreback_money.doubleValue();
                detailDTO.setCommission(String.format("%.2f", commission)); //用户返佣
                detailDTO.setUpcommission(String.format("%.2f", upcommission));//上级返佣
                //店铺名
                detailDTO.setStoreName(detail.containsKey("mall_name") == true ? detail.getString("mall_name") : "");
                result.add(detailDTO);
            }
        }
        //重新排序
        List collect = pddSort(result, sortType);

        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), collect);
    }

    /**
     * 拼多多商品详情
     */
    @Override
    public Tip goodsDetail(String ids, Integer user_id, HttpServletRequest request, String deviceT, String app_version) throws Exception {
        String resultStr = getPddDetail(ids);
        //存放处理后的数据
        GoodsDetailDTO detailDTO = new GoodsDetailDTO();
        if (!StringUtils.isEmpty(deviceT) && Integer.valueOf(deviceT) == 1) {//ios过审版
            detailDTO = filterGoodsUtil.filterIOSVersion(detailDTO, request, app_version);
        }
        SimpleDateFormat smf = new SimpleDateFormat("yyyy-MM-dd");
        if (!StringUtils.isEmpty(resultStr)) {
            JSONObject resultObj = JSON.parseObject(resultStr);
            if (!resultObj.containsKey("goods_detail_response")) {
                throw new BussinessException(BizExceptionEnum.GOODS_INFO_IS_NULL);
            }
            detailDTO.setType(3);
            JSONObject detail = (JSONObject) resultObj.getJSONObject("goods_detail_response").getJSONArray("goods_details").get(0);
            detailDTO.setGoodsId(detail.getString("goods_id"));
            JSONArray images = detail.getJSONArray("goods_gallery_urls");
            List<String> resultList = new ArrayList();
            images.stream().forEach(t -> resultList.add(String.valueOf(t)));
            detailDTO.setGoodsCarouselPictures(resultList);
            detailDTO.setGoodsMainPicture(detail.getString("goods_image_url"));
            detailDTO.setGoodsDesc(detail.getString("goods_desc") == null ? "" : detail.getString("goods_desc"));
            detailDTO.setGoodsName(detail.getString("goods_name"));
            double coupon = detail.getDouble("coupon_discount") / 100;
            detailDTO.setCoupon(String.format("%.2f", coupon));// 优惠卷的价格
            detailDTO.setStoreName(detail.getString("mall_name"));
            detailDTO.setStoreUserId(detail.getInteger("mall_id") + "");

            // 卷的开始
            String coupon_start_time = "";
            String coupon_end_time = "";
            if (!detail.getString("coupon_end_time").equals("0")) {
                coupon_start_time = smf.format(new Date(new Long(detail.getString("coupon_start_time")) * 1000));
            }
            detailDTO.setCouponStartTime(coupon_start_time);
            // 卷的结束

            if (!detail.getString("coupon_end_time").equals("0")) {
                coupon_end_time = smf.format(new Date(new Long(detail.getString("coupon_end_time")) * 1000));
            }
            //是否有卷
            String has_coupon = detail.getString("has_coupon");
            Boolean has_couponBot = false;
            if (null != has_coupon && !has_coupon.equals("")) {
                has_couponBot = has_coupon != "true" ? false : true;
            }
            detailDTO.setIfCoupon(has_couponBot);
            detailDTO.setCouponEndTime(coupon_end_time);
            Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);//公司返佣比例
            Double promotion_rate = detail.getDouble("promotion_rate"); //比例 千分比
            Double min_group_price = Double.valueOf(detail.getString("min_group_price")) / 100;//最小拼团价格 单位分

            // 原价
            String sold_quantity = detail.getString("sales_tip");
            detailDTO.setSales(sold_quantity);//商品月销量
            detailDTO.setPrice(String.format("%.2f", min_group_price));
            //领劵后的价格
            Double price_after_coupon = min_group_price;
            if (has_couponBot) {
                price_after_coupon = price_after_coupon - coupon;
            }
            detailDTO.setPriceAfterCoupon(String.format("%.2f", price_after_coupon));
            // 反拥金    购买赚
            Double commission = promotion_rate / 1000 * price_after_coupon * reback_money.doubleValue();
            Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
            Double upcommission = promotion_rate / 1000 * price_after_coupon * upreback_money.doubleValue();
            String vipDesc = filterGoodsUtil.vipDesc(upcommission,user_id);
            detailDTO.setVipDesc(vipDesc);
            detailDTO.setCommission(String.format("%.2f", commission));
            detailDTO.setUpcommission(String.format("%.2f", upcommission));

            //相关推荐
            int opt_id = detail.containsKey("opt_id") && null != detail.getString("opt_id") ? detail.getInteger("opt_id") : -1;
            detailDTO.setRelatedRecommendation(RelatedRecommendationList(1, opt_id));
            //店铺信息
            Map<String, Object> storeGiveAMark = new HashMap<String, Object>();
            storeGiveAMark.put("storeName", detailDTO.getStoreName());
            storeGiveAMark.put("storeUserId", detailDTO.getStoreUserId());
            storeGiveAMark.put("storeIcon", detailDTO.getStoreIcon());
            storeGiveAMark.put("storeURL", detailDTO.getStoreURL());
            detailDTO.setStoreGiveAMark(storeGiveAMark);
            //H5URL
            detailDTO.setH5Url("");
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), detailDTO);
    }

    public String getPddDetail(String ids) throws Exception {
        Map<String, Object> map = new HashMap<>();//装所有参数，进行转换
        String data_type = "JSON";//响应格式
        String type = "pdd.ddk.goods.detail";//API接口名称
        String timestamp = getSecondTimestamp(new Date());//到秒的时间戳
        String client_id = pddPropertyConfig.getClientId();
        map.put("data_type", data_type);
        map.put("type", type);
        map.put("timestamp", timestamp);
        map.put("client_id", client_id);
        JSONArray goodsIdarr = new JSONArray();
        goodsIdarr.add(ids);
        map.put("goods_id_list", goodsIdarr);
        String sign = StringUtil.sortByMapKey(map, pddPropertyConfig.getClientSecret());//进行转换，返回md5加密的大写
        map.put("sign", sign);
        String entity = ("client_id=" + client_id + "&type=" + type + "&data_type=" + data_type + "&timestamp=" +
                timestamp + "&sign=" + sign + "&goods_id_list=" + goodsIdarr);
        return HttpConnectionPoolUtil.postCommandFromNet2(pddPropertyConfig.getPddsearchUrl(), entity);
    }

    /**
     * 商品相关： 查询店铺商品
     */
    private List<GoodsDetailDTO> RelatedRecommendationList(int page, int opt_id) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String data_type = "JSON";//响应格式
        String type = "pdd.ddk.goods.search";//API接口名称
        String timestamp = StringUtil.getSecondTimestamp(new Date());//到秒的时间戳
        String client_id = pddPropertyConfig.getClientId();
        map.put("type", type);
        map.put("client_id", client_id);
        map.put("page", page);
        map.put("page_size", 20);
        map.put("timestamp", timestamp);
        map.put("data_type", data_type);
        map.put("opt_id", opt_id);
        String sign = StringUtil.sortByMapKey(map, pddPropertyConfig.getClientSecret());//进行转换，返回md5加密的大写
        String entity = ("client_id=" + client_id + "&type=" + type + "&data_type=" + data_type + "&page=" +
                page + "&page_size=20&timestamp=" + timestamp + "&sign=" + sign + "&opt_id=" + opt_id);
        String resultStr = HttpConnectionPoolUtil.postCommandFromNet2(pddPropertyConfig.getPddsearchUrl(), entity);
        //pdd返回数据处理
        List<GoodsDetailDTO> goodsDetailDTOList = new ArrayList<GoodsDetailDTO>();
        if (!StringUtils.isEmpty(resultStr)) {
            JSONObject resultObj = JSON.parseObject(resultStr);
            JSONArray arrs = resultObj.getJSONObject("goods_search_response").getJSONArray("goods_list");
            Map config = commonMapper.getConfigInfo();
            for (Object info : arrs) {
                JSONObject detail = (JSONObject) info;
                GoodsDetailDTO detailDTO = new GoodsDetailDTO();
                Double promotion_rate = detail.getDouble("promotion_rate"); //比例 千分比
                Double min_group_price = detail.getDouble("min_group_price");//最小拼团价格 单位分
                Double myDRD = ((BigDecimal) config.get("reback_money")).doubleValue(); //公司返佣比例
                Double coupon_discount = detail.getDouble("coupon_discount") / 100;//优惠卷价格


                detailDTO.setType(3);
                detailDTO.setGoodsName(detail.getString("goods_name") == null ? "" : detail.getString("goods_name"));
                detailDTO.setGoodsId(detail.getString("goods_id") == null ? "" : detail.getString("goods_id"));
                detailDTO.setGoodsMainPicture(detail.getString("goods_thumbnail_url") == null ? "" : detail.getString("goods_thumbnail_url"));
                detailDTO.setGoodsDesc(detail.getString("goods_desc") == null ? "" : detail.getString("goods_desc"));
                detailDTO.setCoupon(String.format("%.2f", coupon_discount));// 优惠卷
                //计算
                Double original_price = min_group_price / 100; //原价
                detailDTO.setPrice(String.format("%.2f", original_price));
                //是否有优惠卷
                Boolean has_coupon = detail.getBoolean("has_coupon");
                detailDTO.setIfCoupon(has_coupon);
                //领劵后的价格
                Double price_after_coupon = original_price - (has_coupon == true ? coupon_discount : 0);
                detailDTO.setPriceAfterCoupon(String.format("%.2f", price_after_coupon));
                String sales_tip = detail.getString("sales_tip");// 销量
                if (sales_tip == null) {
                    detailDTO.setSales("0");// 销量
                } else {
                    detailDTO.setSales(sales_tip);// 销量
                }
                // 反拥金
                Double anti_growth = (promotion_rate / 1000) * (min_group_price / 100) * (myDRD / 100);
                detailDTO.setCommission(String.format("%.2f", anti_growth));
                //店铺名
                detailDTO.setStoreName(detail.containsKey("mall_name") == true ? detail.getString("mall_name") : "");
                goodsDetailDTOList.add(detailDTO);
            }
        }
        return goodsDetailDTOList;
    }

    /**
     * 拼多多推广位链接
     *
     * @param user_id
     * @param goods_id
     * @return
     */
    @Override
    public Tip getPddUrl(String user_id, String goods_id, String buytype) throws Exception {
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(goods_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        String pId = pddPropertyConfig.getPid();
        if (!StringUtils.isEmpty(buytype) && buytype.equals("1")) {//1 分享购
            pId = pddPropertyConfig.getChannelId();
        }
        Map<String, Object> map = new HashMap<>();//装所有参数，进行转换
        String data_type = "JSON";//响应格式
        String type = "pdd.ddk.goods.promotion.url.generate";//多多进宝推广链接生成API接口
        String timestamp = getSecondTimestamp(new Date());//到秒的时间戳
        String client_id = pddPropertyConfig.getClientId();
        map.put("data_type", data_type);
        map.put("type", type);
        map.put("timestamp", timestamp);
        map.put("client_id", client_id);
        map.put("p_id", pId);
        map.put("custom_parameters", user_id);
        JSONArray goodsIdarr = new JSONArray();
        goodsIdarr.add(goods_id);
        map.put("goods_id_list", goodsIdarr);
        String sign = StringUtil.sortByMapKey(map, pddPropertyConfig.getClientSecret());//进行转换，返回md5加密的大写
        String entity = ("client_id=" + client_id + "&type=" + type + "&data_type=" + data_type + "&timestamp=" +
                timestamp + "&sign=" + sign + "&goods_id_list=" + goodsIdarr + "&p_id=" + pId + "&custom_parameters=" + user_id);
        String resultStr = HttpConnectionPoolUtil.postCommandFromNet2(pddPropertyConfig.getPddsearchUrl(), entity);
        JSONArray detail = null;
        if (!StringUtils.isEmpty(resultStr)) {
            JSONObject resultObj = JSON.parseObject(resultStr);
            detail = resultObj.getJSONObject("goods_promotion_url_generate_response").getJSONArray("goods_promotion_url_list");
            String mobile_url = detail.getJSONObject(0).getString("mobile_url");
            if (!StringUtils.isEmpty(mobile_url) && mobile_url.contains("%3F")) {
                String[] url = mobile_url.split("%3F");
                String endUrl = url[1];
                String[] param = url[0].split("\\?");
                String http = param[0];
                String[] split = param[1].split("&");
                String launch_url = split[1];
                String use_reload = split[0];
                String httpUrl = http + "?" + launch_url + "?" + use_reload + "&" + endUrl;
                detail.getJSONObject(0).put("mobile_url", httpUrl);
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), detail);
    }

    /**
     * 生成拼多多红包推广链接
     */
    public Tip pddRedpacket(String user_id) throws Exception {
        if (StringUtils.isEmpty(user_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        Map<String, Object> map = new HashMap<>();//装所有参数，进行转换
        String generate_short_url = "true";//是否生成短链接。true-是，false-否，默认false
        String generate_weapp_webview = "false";//是否唤起微信客户端， 默认false 否，true 是
        String type = "pdd.ddk.rp.prom.url.generate";//多多进宝推广链接生成API接口
        String data_type = "JSON";//响应格式
        String timestamp = getSecondTimestamp(new Date());//到秒的时间戳
        String pId = pddPropertyConfig.getPid();//自购pid
        String client_id = pddPropertyConfig.getClientId();
        String client_secret = pddPropertyConfig.getClientSecret();
        JSONArray p_id_list = new JSONArray();
        map.put("client_id", client_id);
        map.put("type", type);
        map.put("data_type", data_type);
        map.put("timestamp", timestamp);
        map.put("generate_weapp_webview", generate_weapp_webview);
        map.put("custom_parameters", user_id);
        p_id_list.add(pId);
        map.put("p_id_list", p_id_list);
        String sign = StringUtil.sortByMapKey(map, client_secret);//进行转换，返回md5加密的大写
        String entity = ("client_id=" + client_id + "&type=" + type + "&data_type=" + data_type + "&timestamp=" +
                timestamp + "&generate_weapp_webview=" + generate_weapp_webview + "&sign=" + sign
                + "&p_id_list=" + p_id_list + "&custom_parameters=" + user_id);
        String resultStr = HttpConnectionPoolUtil.postCommandFromNet2(pddPropertyConfig.getPddsearchUrl(), entity);
        if (!StringUtils.isEmpty(resultStr)) {
            JSONObject data = JSON.parseObject(resultStr);
            JSONObject json = data.getJSONObject("rp_promotion_url_generate_response").getJSONArray("url_list").getJSONObject(0);
            String url = json.getString("url");
            if (StringUtils.isEmpty(url)) {
                url = json.getString("mobile_url");
            }
            return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), url);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }

    /**
     * 生成拼多多主题推广链接
     */
    public Tip pddThemeUrl(String user_id,Long theme_id) throws Exception {
        if (StringUtils.isEmpty(user_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        String url = "";

        String pId = pddPropertyConfig.getPid();//自购pid
        String client_id = pddPropertyConfig.getClientId();
        String client_secret = pddPropertyConfig.getClientSecret();

        PopClient client = new PopHttpClient(client_id, client_secret);
        PddDdkThemePromUrlGenerateRequest request = new PddDdkThemePromUrlGenerateRequest();
        request.setPid(pId);
        List<Long> theme_id_list = new ArrayList<>();
        theme_id_list.add(theme_id);//主题ID列表,例如[1,235]
        request.setThemeIdList(theme_id_list);
        request.setCustomParameters(user_id);
        request.setGenerateShortUrl(true);
        PddDdkThemePromUrlGenerateResponse response = client.syncInvoke(request);
        String str = JsonUtil.transferToJson(response);
        if (!StringUtils.isEmpty(str)){
            JSONObject data = JSON.parseObject(str);
            if (data.containsKey("error_response")){//错误时
                JSONObject error_response = data.getJSONObject("error_response");
                Integer error_code = error_response.getInteger("error_code");
                String error_msg = error_response.getString("error_msg");
                return ResultUtil.result(error_code, error_msg);
            }
            JSONArray url_list = data.getJSONObject("theme_promotion_url_generate_response").getJSONArray("url_list");
            if (null == url_list || url_list.size() < 1){
                return ResultUtil.result(BizExceptionEnum.GOODS_ACTIVITY_EMPTY.getCode(),BizExceptionEnum.GOODS_ACTIVITY_EMPTY.getMessage());
            }
            JSONObject detail = url_list.getJSONObject(0);
            url = detail.getString("url");
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(),url);
    }

    /**
     * 获取拼多多主题推广活动主题id
     */
    @Override
    public Tip getThemeid(String name) throws Exception{
        //获取主题列表，通过name匹配需要转链的主题id
        String client_id = pddPropertyConfig.getClientId();
        String client_secret = pddPropertyConfig.getClientSecret();
        PopClient client = new PopHttpClient(client_id, client_secret);
        PddDdkThemeListGetRequest listRequest = new PddDdkThemeListGetRequest();
        listRequest.setPageSize(50);
        listRequest.setPage(1);
        PddDdkThemeListGetResponse listResponse = client.syncInvoke(listRequest);
        String dataStr = JsonUtil.transferToJson(listResponse);
        final Long[] theme_id = {0L};
        if (!StringUtils.isEmpty(dataStr)){
            JSONObject data = JSON.parseObject(dataStr);
            if (data.containsKey("error_response")){//错误时
                JSONObject error_response = data.getJSONObject("error_response");
                String error_msg = error_response.getString("error_msg");
                Integer error_code = error_response.getInteger("error_code");
                return ResultUtil.result(error_code, error_msg);
            }
            JSONArray theme_list = data.getJSONObject("theme_list_get_response").getJSONArray("theme_list");
            if (null == theme_list || theme_list.size() < 1){
                return ResultUtil.result(BizExceptionEnum.GOODS_ACTIVITY_EMPTY.getCode(),BizExceptionEnum.GOODS_ACTIVITY_EMPTY.getMessage());
            }
            theme_list.stream().forEach(t ->{
                JSONObject detail = (JSONObject) t;
                String theme_name = detail.getString("name");
                Long id = detail.getLong("id");
                if (theme_name.contains(name)){
                    theme_id[0] = id;
                }
            });
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(),theme_id[0]);
    }

    /**
     * 订单状态转换
     *
     * @param status
     * @return int
     */
    public Integer reStatus(Integer status) {
        // -1 未支付; 0-已支付；1-已成团；2-确认收货；3-审核成功；4-审核失败（不可提现）；5-已经结算；8-非多多进宝商品（无佣金订单
        if (status == 0 || status == 1 || status == 2 || status == 3) {//已经付款
            return 2;
        } else if (status == 5) { //已经结算
            return 1;
        } else {  //失效
            return 4;
        }
    }

    /**
     * 拼多多最后更新时间段增量同步推广订单信息
     */
    public List getPddOrderList(String start_time, String end_time) throws Exception {
        Map<String, Object> map = new HashMap<>();//装所有参数，进行转换
        JSONArray orderList = new JSONArray();
        int totalPage = 1;//总页数
        String data_type = "JSON";//响应格式
        String type = "pdd.ddk.order.list.increment.get";//API接口名称
        String timestamp = getSecondTimestamp(new Date());//到秒的时间戳
        String client_id = pddPropertyConfig.getClientId();
        map.put("data_type", data_type);
        map.put("type", type);
        map.put("timestamp", timestamp);
        map.put("client_id", client_id);
        map.put("start_update_time", start_time);
        map.put("end_update_time", end_time);

        for (int i = 1; i <= totalPage; i++) {
            Integer page = i;
            map.put("page", page);//默认每页大小为100条数据
            String sign = StringUtil.sortByMapKey(map, pddPropertyConfig.getClientSecret());//进行转换，返回md5加密的大写
            String entity = ("client_id=" + client_id + "&type=" + type + "&data_type=" + data_type + "&timestamp=" +
                    timestamp + "&sign=" + sign + "&start_update_time=" + start_time + "&end_update_time=" + end_time + "&page=" + page);
            String resultStr = HttpConnectionPoolUtil.postCommandFromNet2(pddPropertyConfig.getPddsearchUrl(), entity);
            if (!StringUtils.isEmpty(resultStr)) {
                JSONObject resultObj = JSON.parseObject(resultStr);
                JSONArray result = resultObj.getJSONObject("order_list_get_response").getJSONArray("order_list");
                Double totalCount = resultObj.getJSONObject("order_list_get_response").getDouble("total_count");
                totalPage = (int) Math.ceil(totalCount / 100);//默认每页大小为100条数据
                orderList.addAll(result);
            }
        }
        logger.info("**********拼多多获取总订单数量为：【" + orderList.size() + "】**********");
        return orderList;
    }

    /**
     * 拼多多支付时间段增量同步推广订单信息
     */
    public List getPddOrderListByPayTime(String start_time, String end_time) throws Exception {
        JSONArray orderList = new JSONArray();
        String last_order_id = "";
        String client_id = pddPropertyConfig.getClientId();
        String clientSecret = pddPropertyConfig.getClientSecret();
        PddDdkOrderListRangeGetRequest request = new PddDdkOrderListRangeGetRequest();
        PopClient client = new PopHttpClient(client_id, clientSecret);
        request.setStartTime(start_time);
        request.setLastOrderId(last_order_id);
        request.setPageSize(300);
        request.setEndTime(end_time);
        PddDdkOrderListRangeGetResponse response = client.syncInvoke(request);
        String strData = JsonUtil.transferToJson(response);
        JSONObject data = JSON.parseObject(strData);
        if (data.containsKey("error_response")){
            logger.info("【拼多多获取订单错误："+ data.getJSONObject("error_response").getString("error_msg") + "】");
        }else {
            JSONObject order_list_get_response = data.getJSONObject("order_list_get_response");
            last_order_id = order_list_get_response.getString("last_order_id");
            if (order_list_get_response.containsKey("order_list")){
                orderList = order_list_get_response.getJSONArray("order_list");
            }
        }
        logger.info("**********拼多多获取总订单数量为：【" + orderList.size() + "】**********");
        return orderList;
    }

    /**
     * pdd数据重新排序
     *
     * @param list
     * @param sort_type
     * @return
     */
    private static List pddSort(List list, String sort_type) throws Exception {
        List collect = new ArrayList();
        switch (sort_type) {
            case "6": // 按销量降序 优惠卷升序
                collect = (ArrayList) list.stream().sorted(Comparator.comparing(GoodsDetailDTO::getSales)).collect(Collectors.toList());
                break;
            case "0": // 综合排序   按销量降序
                collect = (ArrayList) list.stream().sorted(Comparator.comparing(GoodsDetailDTO::getSales).reversed()).collect(Collectors.toList());
                break;
            case "7": // 优惠卷升序
                collect = (ArrayList) list.stream().sorted(Comparator.comparing(GoodsDetailDTO::getCoupon)).collect(Collectors.toList());
                break;
            case "8": // 优惠卷降序
                collect = (ArrayList) list.stream().sorted(Comparator.comparing(GoodsDetailDTO::getCoupon).reversed()).collect(Collectors.toList());
                break;
            case "9": //  到手价升序
                collect = (ArrayList) list.stream().sorted(Comparator.comparing(GoodsDetailDTO::getPriceAfterCoupon)).collect(Collectors.toList());
                break;
            default:
                collect.addAll(list);
                break;
        }
        return collect;
    }
}
